﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace screen_socket_clioent
{
    public partial class Form1 : Form
    {
        Socket clientSocket;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
              string ipPort = configBox.Text;
            string[] config = ipPort.Split(':');
            if (config.Length!=2)
            {
                MessageBox.Show("请输入正确的ip和端口号!");
                return;
            }
            string IP = config[0];
            int port = Convert.ToInt32(config[1]);
            try
            {
                IPAddress ip = IPAddress.Parse(IP);
                  clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(new IPEndPoint(ip, port));
                Thread imageUpdate = new Thread(update);
                imageUpdate.Start(clientSocket);
               
            }
            catch (Exception ex)
            {
                MessageBox.Show("建立连接失败，请重试！");
            }
        }

        private void update(object clientSocket)
        {
            Socket client = (Socket)clientSocket;
            int receiveNumber;
            byte[] buffer;
            byte[] image;
            while (true)
            {
                //先发送一个确认连接包
                buffer = new byte[1];
                buffer[0] = 1;
                client.Send(buffer);
                //先记录数据的大小，再申请对应大小的缓冲区
                buffer = new byte[4];
                receiveNumber = client.Receive(buffer);
                int dataLength =  BitConverter.ToInt32(buffer, 0);
                client.Send(buffer);
                buffer = new byte[4096];
                image = new byte[dataLength];
                GC.Collect();
                int offset = 0;
                while (offset != dataLength)
                {
                    receiveNumber = client.Receive(buffer);
                    Buffer.BlockCopy(buffer, 0, image, offset, receiveNumber);
                    offset += receiveNumber;
                }
                pictureBox1.Image = getBitmap(image);
            }
        }
 
        private Bitmap getBitmap(byte[] bytesData)
        {
            MemoryStream ms1 = new MemoryStream(bytesData);
            Bitmap bm = (Bitmap)Image.FromStream(ms1);
            ms1.Close();
            return bm;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            clientSocket.Close();
        }
         
    }
}
